package com.huanwang.commonlibrary.networkframework

import com.huanwang.commonlibrary.base.BaseApplication
import okhttp3.Cache
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.io.File
import java.util.concurrent.TimeUnit

/**
 * @author wang_hong_wei
 * @description Retrofit的封装类
 * @Date 2018-5-11
 */
object RetrofitClient {
    var mRetrofit: Retrofit? = null

    //接口对象的单例实现
    fun getInstance(): Retrofit? {
        if (mRetrofit == null) synchronized(RetrofitClient::class.java) {
            if (mRetrofit == null) {
                val cacheFile =
                    File(BaseApplication.context!!.externalCacheDir, "RetrofitCache")
                if (!cacheFile.exists()) {
                    try {
                        cacheFile.mkdir()
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                }
                val cache = Cache(cacheFile, 1024 * 1024 * 50)
                //创建OKHttpClient的对象
                val builder = OkHttpClient.Builder()
                // Log信息拦截器
                val logging =
                    HttpLoggingInterceptor(object : HttpLoggingInterceptor.Logger {
                        override fun log(message: String) {
                            //Logger.t(TAG).i(message);
                        }
                    })
                logging.setLevel(HttpLoggingInterceptor.Level.BODY)
                builder.addInterceptor(logging)
                val okHttpClient =
                    builder.retryOnConnectionFailure(true) //连接失败后是否重新连接
                        .connectTimeout(5000, TimeUnit.SECONDS)
                        .readTimeout(5000, TimeUnit.SECONDS)
                        .writeTimeout(5000, TimeUnit.SECONDS)
                        .cache(cache)
                        .addNetworkInterceptor(OKhttpInterceptor.cacheInterceptor)
                        .addInterceptor(OKhttpInterceptor.commonParamsInterceptor)
                        .build()
                //获取接口的对象
                mRetrofit = Retrofit.Builder()
                    .baseUrl(RetrofitPath.BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create()) //添加gson转换器
                    .addCallAdapterFactory(RxJava3CallAdapterFactory.create()) //添加rxjava转换器
                    .client(okHttpClient)
                    .build()
            }
        }
        return mRetrofit
    }
}